<template>
  <div class="login-container">
    <div class="logo" />
    <div class="form">
      <h1>登录</h1>

      <el-card shadow="never" class="login-card">
        <!--登录表单-->
        <!-- el-form > el-form-item > el-input -->
        <el-form v-if="currentLogin === 'phone'" ref="form" :model="loginForm" :rules="loginRules">
          <el-form-item prop="mobile">
            <el-input v-model="loginForm.mobile" placeholder="请输入手机号" />
          </el-form-item>

          <el-form-item prop="password">
            <el-input v-model="loginForm.password" show-password placeholder="请输入密码" />
          </el-form-item>

          <el-form-item prop="isAgree">
            <el-checkbox v-model="loginForm.isAgree">
              用户平台使用协议
            </el-checkbox>

          </el-form-item>

          <el-form-item>
            <el-button style="width:350px" type="primary" @click="submit">登录</el-button>
            <!-- <el-button @click="test">测试</el-button> -->

          </el-form-item>

        </el-form>
        <div v-else-if="currentLogin === 'qrcode'" class="qrcode-login">
          <div v-if="codeState === 4" class="qrcode_layer timeout">
            <span>点击刷新</span>
            <i class="el-icon-refresh-left" @click="createQrCode" />
          </div>
          <div v-if="codeState === 5" class="qrcode_layer timeout">
            <span>用户已取消</span>
            <i class="el-icon-refresh-left" @click="createQrCode" />
          </div>
          <div v-if="codeState === 2" class="qrcode_layer scan_success">
            <span>扫描成功</span>
            <i class="el-icon-check" />
          </div>
          <canvas ref="qrcodeCanvas" />
        </div>
        <div class="multi-login">
          <el-button size="small" class="multi-button" @click="currentLogin = 'phone'">手机号登录</el-button>
          <el-button size="small" class="multi-button" @click="currentLogin = 'qrcode'">扫码登录</el-button>
        </div>

      </el-card>
    </div>
  </div>

</template>

<script>
import { getQrCodeKey, getQrCodeState } from '@/api/user'
import instance from '@/utils/request'
import QrCode from 'qrcode'

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        mobile: process.env.NODE_ENV === 'development' ? '13800000002' : '',
        password: process.env.NODE_ENV === 'development' ? 'hm#qd@23!' : '',
        isAgree: process.env.NODE_ENV === 'development'
      },
      loginRules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '密码长度在6到16位之间', trigger: 'blur' }
        ],
        isAgree: [
          {
            validator: (rule, value, callback) => {
              value ? callback() : callback(new Error('请勾选用户平台使用协议'))
            }
          }
        ]
      },
      currentLogin: 'phone', // phone/qrcode
      qrCodeKey: '', // 声明一个加密串的变量
      codeState: 1
    }
  },
  watch: {
    currentLogin(newValue) {
      if (newValue === 'qrcode') {
        this.createQrCode() // 生成二维码
      } else {
        clearInterval(this.timer) // 只要不是扫码登录就停止
      }
    }
  },
  // 卸载前先把定时器取消掉
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    // 生成二维码
    async createQrCode() {
      this.codeState = 1 // 回到初始状态
      // 只要切换到扫码就换新的密钥
      this.$nextTick(async() => {
        await this.getQrCodeKey()
        this.beginLoopCheck() // 开启轮询
        // 使用QrCode的toCanvas方法将加密串生成二维码
        QrCode.toCanvas(this.$refs.qrcodeCanvas, this.qrCodeKey, {
          width: 280, // 设置二维码的宽300
          height: 280 // 设置二维码的高300;
        })
      })
    },
    // 获取加密串的方法
    async getQrCodeKey() {
      this.qrCodeKey = await getQrCodeKey()
    },
    // 开始轮询
    beginLoopCheck() {
      const checkState = async() => {
        try {
          const { codeState, token } = await getQrCodeState({ qrcode_key: this.qrCodeKey })
          this.codeState = codeState
          // 4 和 5是直接停止
          if (this.codeState === 4 || this.codeState === 5) {
            clearInterval(this.timer)
          } else if (this.codeState === 3) {
            // 3 是停止之后要登录
            clearInterval(this.timer)
            this.$store.commit('user/setToken', token) // 登录设置token
            this.$router.push('/') // 跳转到主页
          }
        } catch (error) {
          clearInterval(this.timer) // 异常的时候停止
        }
      }
      this.timer = setInterval(() => {
        checkState()
      }, 2000)
    },
    // 登录
    async submit() {
      await this.$refs.form.validate()
      await this.$store.dispatch('user/login', this.loginForm)
      this.$router.push('/')
    },
    async test() {
      const res = await instance.post('/sys/login', this.loginForm)
      console.log(res)
    }
  }
}
</script>

<style lang="scss">
.login-container {
  display: flex;
  align-items: stretch;
  height: 100vh;

  .logo {
    flex: 3;
    background: rgba(38, 72, 176) url(../../assets/common/login_back.png) no-repeat center / cover;
    border-top-right-radius: 60px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    justify-content: center;
    padding: 0 100px;

    .icon {
      background: url(../../assets/common/logo.png) no-repeat 70px center / contain;
      width: 300px;
      height: 50px;
      margin-bottom: 50px;
    }

    p {
      color: #fff;
      font-size: 18px;
      margin-top: 20px;
      width: 300px;
      text-align: center;
    }
  }

  .form {
    flex: 2;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding-left: 176px;

    .el-card {
      border: none;
      padding: 0;
    }

    h1 {
      padding-left: 20px;
      font-size: 24px;
    }

    .el-input {
      width: 350px;
      height: 44px;

      .el-input__inner {
        background: #f4f5fb;
      }
    }

    .el-checkbox {
      color: #606266;
    }

    .multi-login {
      margin: 10px 0;
      display: flex;
      width: 350px;

      .multi-button {
        flex: 1;
      }
    }
  }

  .qrcode-login {
    width: 350px;
    padding: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
  }
  .qrcode_layer {
    position: absolute;
    width: 150px;
    height: 150px;
    left: 50%;
    top: 50%;
    transform: translate(-75px, -75px);
    opacity: 0.9;
    background: #e1dede;
    display: flex;
    justify-content: center;
    align-items: center;
    i {
      font-size: 40px;
      padding: 10px;
    }
  }
  .scan_success {
    i {
      color: #67C23A;
    }
  }
  .timeout {
    i {
      color: #F56C6C;
    }
  }
}
</style>
